# -*- coding: utf-8 -*-
"""
@Time：YourTime
@Author  : YourName
@Desc    :
"""
from fastapi import APIRouter, Query, HTTPException
from orm.models import *
from pydantic import BaseModel, Field, field_validator
from tortoise.exceptions import DoesNotExist
from fastapi import status

api_bug = APIRouter()


class BugCreate(BaseModel):
    bug_name: str = Field(..., title="bug名称", description='bug的名称')
    bug_desc: str = Field(default=None,
                          title="bug描述",
                          description='描述bug的一些基本信息')
    bug_creator: str = Field(..., title="bug创建者", description='创建bug的人')
    bug_assignee: str = Field(..., title="bug负责人", description='负责处理bug的人')
    test_depart_id: int = Field(default=None,
                                title="测试部门id",
                                description='测试部门的id')
    product_depart_id: int = Field(default=None,
                                   title="产品部门id",
                                   description='产品部门的id')

    @field_validator('test_depart_id')
    async def validate_bug_name(cls, v, values):
        if v is None:
            raise ValueError("测试部门ID不能为空")
        try:
            test_depart = await Department.get(id=v)
        except DoesNotExist:
            raise ValueError("测试部门不存在")
        if not await test_depart.members.filter(name=values['bug_creator']
                                                ).exists():
            raise ValueError(
                f"创建者 '{values['bug_creator']}' 不在测试部门 '{test_depart.name}' 的成员中"
            )
        return v


class TestDepartInfo(BaseModel):
    name: str = Field(..., title="部门名称", description='部门名称')
    hobby: str = Field(..., title="部门爱好", description='部门爱好')


class TestEmployeeInfo(BaseModel):
    employee_name: str = Field(..., title="员工名称", description='员工名称')
    employee_hobby: str = Field(..., title="员工爱好", description="员工爱好")
    department_id: int = Field(..., description="部门ID")


@api_bug.get('/bug/list')
async def getbuglist():
    bug_info = await Bug_Info.all()
    return bug_info


@api_bug.post('/bug/create')
async def create_bug(bug: BugCreate):
    # 创建bug实例
    new_bug = await Bug_Info.create(bug_name=bug.bug_name,
                                    bug_desc=bug.bug_desc,
                                    bug_creator=bug.bug_creator,
                                    bug_assignee=bug.bug_assignee,
                                    test_depart=bug.test_depart_id,
                                    product_depart=bug.product_depart_id)
    return {
        "code": 200,
        "msg": "success",
        "id": new_bug.id,
        "bug_name": new_bug.bug_name,
        "bug_desc": new_bug.bug_desc,
        "bug_creator": new_bug.bug_creator,
        "bug_assignee": new_bug.bug_assignee
    }


@api_bug.post('/bug/xbase_depart/create',
              status_code=status.HTTP_200_OK,
              description="创建部门")
async def create_xbase_depart_info(depart: TestDepartInfo):
    test_info = await Department.create(depart_name=depart.name,
                                        depart_hobby=depart.hobby)
    return {
        "code": status.HTTP_200_OK,
        "msg": "success",
        "name": test_info.depart_name
    }


@api_bug.post('/bug/xbase_depart/employee/create',
              status_code=status.HTTP_200_OK,
              description="创建部门员工")
async def create_department_employee_info(employee: TestEmployeeInfo):
    employee_res = await Employee.create(name=employee.employee_name,
                                         department_id=employee.department_id,
                                         hobby=employee.employee_hobby)

    return {
        "status": status.HTTP_200_OK,
        "message": "success",
        "data": employee_res
    }


@api_bug.get('/bug/xbase_depart/list',
             status_code=status.HTTP_200_OK,
             description="部门列表")
async def get_test_depart_info(department_name: str = Query(
    None, description="部门名称")):
    if department_name:
        department = await Department.filter(depart_name=department_name
                                             ).first()
        if not department:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                                detail="部门:{}不存在".format(department_name))
        employee = await department.employee.all()
        return {
            "code": status.HTTP_200_OK,
            "message": "success",
            "data": {
                "department": department,
                "employee": employee
            }
        }
    else:
        #如果不传department_name，就获取所有部门信息
        all_department = await Department.all()
        return {
            "code": status.HTTP_200_OK,
            "message": "success",
            "data": all_department
        }


@api_bug.get('/bug/test_depart_user/{test_name}',
             status_code=status.HTTP_200_OK)
async def get_test_depart_user_one_info(test_name: str):
    user = await Employee.filter(username=test_name).first()
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail='员工{}不存在'.format(test_name))
